<?php 

	require_once __DIR__."/../Models/user.php";

	use Silex\Application;
	use Symfony\Component\HttpFoundation\Request;
	use Symfony\Component\HttpFoundation\Response;


	$user_model = new Models\User($app);
	$user = $app['controllers_factory'];

	
	class UserTable
	{
		public $page;
		public $limit;
		public $class = "user";
		public $name = "User Table Name";
		public $rows = array();
		public $head = array();
		public $head_model = array();
		public $options = array();
		public $rowsjs;
		public $headjs;
		public $optionsjs;
	}
	
	$table = new UserTable();

	$user->get('/', function(Request $request) use ($app, $user_model, $table){
		$res = $user_model->getAll();
		$i = 0;

		foreach ($res as $val) {
			$table->rows[$i]['id']	 = $val["user_id"];
			$table->rows[$i]['cell']	 = $val;
			$i++;
		}		

		$table->head = array(
				array('name'=>"user_id", 'display'=>'ID', 'type'=>"int",	'align'=>'right','size'=>'15%',	'edit'=>false, 'new'=>false ),					
				array('name'=>"user_login", 'display'=>'Логин', 'type'=>"string", 'align'=>'center','size'=>'50%',	'edit'=>true, 'new'=>true ),					
				array('name'=>"user_pass", 'display'=>'Пароль Хэш', 'type'=>"text",	'align'=>'left','size'=>'35	%',	'edit'=>true, 'new'=>true),					
			);


		$table->options = array(
				"width" => '750px',
				"url" =>   $app['homepage_route'] . $app['url_generator']->generate('usertable')
			);

		$table->rowsjs = json_encode($table->rows);
		$table->headjs = json_encode($table->head);
		$table->optionsjs = json_encode($table->options);


		return $app['twig']->render('usertable.html', array('table'=>$table));
	})->bind('usertable');
	
	$user->post('/', function(Request $request) use ($app, $user_model, $table){
		$d = $request->get('rows');
		
		$data = array(
			"user_id"=>$request->get('id'), 
			"user_login"=>$d['user_login'], 
			"user_pass"=>$d['user_pass'],
		);

		$oper = $request->get('oper');
		if($oper == 'add'){
			$res = $user_model->inser($data);	
		}elseif($oper == 'edit'){
			$res = $user_model->update($data);
		}elseif($oper == 'del'){
			$res = $user_model->delete($data);
		}elseif($oper == 'read'){
			$res = $user_model->getAll();
		}
		return json_encode($res);
	});

	return $user;

?>